<template>
  <a-modal
    :open="open"
    width="1000px"
    title="医师维护"
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    destroy-on-close
    centered
    :keyboard="false"
    @ok="onOk"
    @cancel="onCancel"
  >
    <div class="h-[500px]">
      <a-tabs v-model:activeKey="tabActiveKey">
        <a-tab-pane key="基本信息" tab="基本信息">
          <!-- pointer-events-none -->
          <a-form :model="formState" :colon="false" class="form-style-flex" :label-col="{ style: { width: '100px' } }">
            <a-form-item label="员工编号" name="empId" class="w-1/3" v-bind="validateInfos.empId">
              <a-input v-model:value="formState.empId" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="员工姓名" class="w-1/3" v-bind="validateInfos.empName">
              <a-input v-model:value="formState.empName" placeholder="请输入" @blur="onChangeEmpName" />
            </a-form-item>
            <a-form-item label="员工性别" class="w-1/3">
              <a-radio-group v-model:value="formState.sex" name="radioGroup">
                <a-radio value="男">男</a-radio>
                <a-radio value="女">女</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="助记码" class="w-1/3" v-bind="validateInfos.zjm">
              <a-input v-model:value="formState.zjm" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="出生日期" class="w-1/3" v-bind="validateInfos.birthday">
              <a-date-picker v-model:value="formState.birthday" value-format="YYYY-MM-DD" />
            </a-form-item>
            <a-form-item label="手机号码" class="w-1/3" v-bind="validateInfos.phone">
              <a-input v-model:value="formState.phone" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="科室名称" class="w-2/3" v-bind="validateInfos.ksdm">
              <a-select v-model:value="formState.ksdm" placeholder="请选择" :options="departmentNameList" allow-clear />
            </a-form-item>
            <a-form-item label="员工类别" class="w-1/3" v-bind="validateInfos.categoryIds">
              <a-select
                v-model:value="formState.categoryIds"
                disabled
                placeholder="请选择"
                mode="multiple"
                :max-tag-count="1"
                :options="employeeCategoryList"
                allow-clear
              />
            </a-form-item>
            <a-form-item label="部门" class="w-full" v-bind="validateInfos.deptmentBh">
              <a-tree-select
                v-model:value="formState.bmmc"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择"
                allow-clear
                tree-default-expand-all
                :tree-data="deptmentTreeList"
                tree-node-filter-prop="label"
                @select="onChangeTree"
              />
            </a-form-item>
            <a-form-item label="备注" class="w-full">
              <a-textarea v-model:value="formState.memo" placeholder="请输入" :auto-size="{ minRows: 8 }" />
            </a-form-item>
            <div class="flex justify-end w-full text-red-500">初始密码：{{ passWord }}</div>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="医师信息" tab="医师信息">
          <a-form :model="formState" :colon="false" class="form-style-flex" :label-col="{ style: { width: '100px' } }">
            <div class="flex w-full">
              <div>
                <a-form-item label="头像" :label-col="{ style: { width: '60px' } }" v-bind="validateInfos.picturePath">
                  <a-upload list-type="picture-card" class="w-0 relative" :show-upload-list="false" :custom-request="beforeUpload">
                    <!-- <ZoomInOutlined v-if="formState.picturePath" class="absolute" style="top: 78px; left: 80px; font-size: 20px" /> -->
                    <img v-if="formState.picturePath" :src="formState.picturePath" class="w-full f-full" alt="avatar" />

                    <div v-else>
                      <loading-outlined v-if="loading" />
                      <div v-else class="flex flex-col items-center">
                        <PlusOutlined />
                        <span class="mt-2">上传照片</span>
                      </div>
                    </div>
                  </a-upload>
                </a-form-item>
              </div>
              <div class="flex flex-wrap flex-1">
                <a-form-item label="职称" class="w-1/2" v-bind="validateInfos.title">
                  <!-- <a-select v-model:value="formState.title" placeholder="请选择" :options="employeeTitleList" allow-clear /> -->
                  <SelectItem v-model:value="formState.title" type="DT00014" placeholder="请选择" allow-clear />
                </a-form-item>
                <a-form-item label="分组" class="w-1/2">
                  <a-select v-model:value="formState.groupId" placeholder="请选择" :options="employeeGroupingList" allow-clear />
                </a-form-item>
                <a-form-item label="职务" class="w-1/2" v-bind="validateInfos.duties">
                  <SelectItem v-model:value="formState.duties" type="DT00016" placeholder="请选择" allow-clear />
                  <!-- <a-select v-model:value="formState.duties" placeholder="请选择" :options="empPositionList" allow-clear /> -->
                </a-form-item>
                <a-form-item label="默认诊室" class="w-1/2">
                  <a-select v-model:value="formState.defaultRoomId" placeholder="请选择" :options="empInfoList" allow-clear />
                </a-form-item>
                <a-form-item label="初诊间隔" class="w-1/3">
                  <a-input v-model:value="formState.firstVisitInterval" v-input:int placeholder="请输入" suffix="分钟" />
                </a-form-item>
                <a-form-item label="复诊间隔" class="w-1/3">
                  <a-input v-model:value="formState.returnVisitInterval" v-input:int placeholder="请输入" suffix="分钟" />
                </a-form-item>
                <a-form-item label="默认西成药药房" class="w-1/3" :label-col="{ style: { width: '120px' } }">
                  <a-select v-model:value="formState.defaultStoreId" placeholder="请选择" :options="defaultStoreIdList" />
                </a-form-item>
                <a-form-item label="排队号标识" class="w-1/3" v-bind="validateInfos.pdhbs">
                  <a-input v-model:value="formState.pdhbs" placeholder="请输入" />
                </a-form-item>
                <a-form-item label="顺序号" class="w-1/3">
                  <a-input v-model:value="formState.outOrde" v-input:int placeholder="请输入" />
                </a-form-item>
                <a-form-item class="w-1/3 pl-32">
                  <a-checkbox v-model:checked="formState.isOnlineAppointment" disabled>开放线上预约</a-checkbox>
                </a-form-item>
                <!-- <a-form-item label="执业证书编号" class="w-2/3">
                  <a-input v-model:value="formState.certNo" v-input:int placeholder="请输入" />
                </a-form-item> -->
              </div>
            </div>
            <a-form-item label="擅长" class="w-full" :label-col="{ style: { width: '60px' } }">
              <a-textarea v-model:value="formState.goodAt" placeholder="请输入" :auto-size="{ minRows: 4 }" />
            </a-form-item>
            <a-form-item label="简介" class="w-full" :label-col="{ style: { width: '60px' } }">
              <a-textarea v-model:value="formState.introduction" placeholder="请输入" :auto-size="{ minRows: 4 }" />
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="抗菌药使用" tab="抗菌药使用">
          <Antibacterial :user-data="formState" @success="onSuccess" />
        </a-tab-pane>
        <a-tab-pane key="挂号费别" tab="挂号费别">
          <Registered :user-data="rowData" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import axios from 'axios'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import SelectItem from '@/components/SelectItem'
import Registered from './Registered.vue'
import Antibacterial from './Antibacterial.vue'

const page = ref({ total: 0, current: 1, pageSize: getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10 })
const { empId } = useUserStore()
const passWord = ref('')
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const tabActiveKey = ref('基本信息')
const defaultStoreIdList = ref()
const deptmentTreeList = ref([])
const departmentNameList = ref([])
// const employeeTitleList = ref([])
const employeeCategoryList = ref([])
const employeeGroupingList = ref([])
// const empPositionList = ref([])
const empInfoList = ref([])
const tableData = ref([])
const loading = ref(false)

const userData = ref({})

const emit = defineEmits(['update:open', 'success'])
const formState = ref({
  sex: '男',
  empId: '',
  empName: '',
  zjm: '',
  birthday: '',
  phone: '',
  ksdm: '',
  categoryId: '',
  categoryIds: [],
  categoryCode: '',
  deptmentBh: null,
  title: null,
  duties: null,
  pdhbs: '',
  photoUrl: '',
  picturePath: ''
})
const rulesState = ref({
  empId: [{ required: true, message: '请输入员工编号' }],
  empName: [{ required: true, message: '请输员工姓名' }],
  zjm: [{ required: true, message: '请输入助记码' }],
  birthday: [{ required: true, message: '请选择出生日期' }],
  phone: [{ required: true, message: '请输入手机号码' }],
  ksdm: [{ required: true, message: '请选择科室' }],
  categoryIds: [{ required: true, message: '请选择员工类别' }],
  title: [{ required: true, message: '请选择职称' }],
  duties: [{ required: true, message: '请选择职务' }],
  pdhbs: [{ required: true, message: '请选择排队号标识' }],
  deptmentBh: [{ required: true, message: '请选择部门' }],
  picturePath: [{ required: true, message: '请上传头像' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)

// 抗菌药使用
const onSuccess = (val) => {
  formState.value.useLevel = val
}

const getEmpInfoList = async () => {
  const { code, data } = await post('operation/opex/getRoomList', {
    pyjm: '',
    pageNum: 1,
    pageSize: 999
  })
  if (code !== 0) return
  empInfoList.value = data.map((item) => {
    return {
      label: item.roomName,
      value: item.roomId
    }
  })
}
const getStoreIdList = async () => {
  const res = await post('/operation/opex/getDrugStoreInfoList', { status: 1, isProducer: '1' })
  if (res.code !== 0) return message.error(res.msg)
  defaultStoreIdList.value = res.data.map((item) => {
    return { label: item.storeName, value: item.id }
  })
}

const queryList = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    pageNum: 1,
    pageSize: getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10
  })
  if (code !== 0) return
  passWord.value = data[0].csmm
}

const onChangeEmpName = async (e) => {
  const { data, code, msg } = await post('/common/util/getPinyin', {
    name: e.target.value
  })
  if (code !== 0) return message.error(msg)
  formState.value.zjm = data
}
const getDeptInfoList = async () => {
  const { code, data } = await post('/outp/mzdj/getDeptInfoList', {
    ksdm: '',
    pyjm: '',
    risbz: '',
    sfylks: ''
  })
  if (code !== 0) return
  departmentNameList.value = data.map((item) => {
    return {
      label: item.ksmc,
      value: item.ksdm
    }
  })
}
// 职称
// const getTitleList = async () => {
//   const { code, data } = await post('/drugStorage/comprehenive/getEmpZc')
//   if (code !== 0) return
//   employeeTitleList.value = data.map((item) => {
//     return {
//       label: item.mc,
//       value: item.bm
//     }
//   })
// }
// 分组
const getEmpTypeList = async () => {
  const { code, data } = await post('/drugStorage/comprehenive/getEmpType')
  if (code !== 0) return
  employeeGroupingList.value = data.map((item) => {
    return {
      label: item.fzmc,
      value: item.fzbh
    }
  })
}
// 员工类别
const getEmpCategoryList = async () => {
  const { code, data } = await post('/drugStorage/comprehenive/getEmpCategory')
  if (code !== 0) return
  employeeCategoryList.value = data.map((item) => {
    return {
      label: item.categoryName,
      value: item.id,
      categoryCode: item.categoryCode
    }
  })
}
// 职位
// const getEmpPositionList = async () => {
//   const { code, data } = await post('/operation/opex/getEmpPositionList')
//   if (code !== 0) return
//   empPositionList.value = data.map((item) => {
//     return {
//       label: item.mc,
//       value: item.bm
//     }
//   })
// }
const getDeptmentTreeList = async () => {
  const { code, data } = await post('/operation/opex/getSystemDeptList', { status: 0 })
  if (code !== 0) return
  deptmentTreeList.value = convertToTreeSelectData(data)
}

const convertToTreeSelectData = (data) => {
  const result = []
  data.forEach((item) => {
    const newItem = {
      label: item.deptName + (item.sl > 0 ? ` (${item.sl})` : ''),
      value: item.id,
      deptName: item.deptName
    }
    if (item.children && item.children.length > 0) {
      newItem.children = convertToTreeSelectData(item.children)
    }
    result.push(newItem)
  })
  return result
}

const onChangeTree = (value, node) => {
  formState.value.bmmc = node.deptName
  formState.value.deptmentBh = value
}

const getRegFeeCategory = async (id) => {
  const { code, data, total } = await post('/operation/opex/getEmpGHFB', {
    empId: id,
    pageNum: page.value.current,
    pageSize: page.value.pageSize
  })
  if (code !== 0) return
  page.value.total = total
  tableData.value = data
}
const beforeUpload = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
  if (!isJpgOrPng) {
    message.error('请上传jpg或者png格式!')
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  const { data: res } = await axios.post('/api/v1/common/util/doUploadFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.code !== 0) return message.error(res.msg)
  formState.value.photoUrl = res.data.fileName
  formState.value.picturePath = res.data.picturePath
}

const onOk = async () => {
  await validate()
  if (!formState.value.empId) return message.error('请填写员工编号')
  formState.value.isOnlineAppointment = formState.value.isOnlineAppointment ? '1' : '0'
  formState.value.categoryCode = employeeCategoryList.value.filter((it) => {
    return it.value === formState.value.categoryIds
  })[0]?.categoryCode
  const { code, msg } = await post('/operation/opex/doSaveEmpInfo', formState.value)
  if (code !== 0) return message.error(msg)
  message.success(msg)
  resetFields()
  emit('success')
}

const onCancel = () => {
  emit('update:open', false)
}

// 获取医师头像真实路径
const getImage = async () => {
  const { code, data, msg } = await post('/common/util/getFileUrl', {
    fileName: formState.value?.photoUrl
  })
  if (code !== 0) return message.error(msg)
  formState.value.picturePath = data?.picturePath
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      tabActiveKey.value = '基本信息'
      if (props.rowData?.id) {
        userData.value = { ...props.rowData, isOnlineAppointment: props.rowData.isOnlineAppointment === '1' ? true : false }
        formState.value = { ...props.rowData, isOnlineAppointment: props.rowData.isOnlineAppointment === '1' ? true : false }
        formState.value.picturePath = props.rowData.picturePath
        formState.value.useLevel = props.rowData.useLevel ? props.rowData.useLevel : '2'
        getRegFeeCategory(props.rowData.empId)
        getImage()
      } else {
        formState.value = { ...props.rowData }
        formState.value.useLevel = '2'
        formState.value.pwd = empId
        formState.value.sex = '男'
        tableData.value = null
      }
    }
  }
)

onMounted(() => {
  // getTitleList()
  getEmpTypeList()
  // getEmpPositionList()
  getEmpInfoList()
  getDeptInfoList()
  getEmpCategoryList()
  getDeptmentTreeList()
  queryList()
  getStoreIdList()
})
</script>
<style lang="less" scoped>
// .avatar-uploader {
//   width: auto;
// }
</style>
